import { Button, Modal, Space, Spin, ImgDefault } from "@bytedance/mona-ui"
import dyrequest from "@Utils/request"
import React, { useState, useRef } from "react"

import { store } from "~store"
import { setAiCretedList } from "~store/controller/jinritemaiCopyGoods"

import AiImage from './AIImage'

import "./index.scss"

let globChangeImage
let setImageTime
function putUpDataFun(data) {
  // console.log('geadUpData0011', data)
  if (setImageTime) return

  try {
    const { aiCretedList } = store.getState()?.jinritemaiCopyGoods
    let imagesUrls: any = []
    data.forEach((inter, inde) => {
      inter[0] && inter[0].imsdata && imagesUrls.push(...inter[0]?.imsdata)
    })
    if (imagesUrls && imagesUrls.length) {
      if (aiCretedList && aiCretedList.length) {
        const gteInter = JSON.parse(JSON.stringify(aiCretedList))
        gteInter.push(...imagesUrls)
        // aiCretedList.push(...imagesUrls)
        store.dispatch(setAiCretedList(gteInter))
      } else {
        store.dispatch(setAiCretedList(imagesUrls))
      }
    }
  } catch (error) {
    console.log("缓存错误", error)
  }

  // console.log('setImageTime是否关闭', setImageTime)
  globChangeImage && globChangeImage(data)
  setImageTime = setTimeout(() => {
    clearTimeout(setImageTime)
    setImageTime = null
  }, 1000)
}
let iframe
let setAddInfoDatass
let wetsetLodinIframe
function lengthcdata(event) {
  try {
    const putDyImage = JSON.parse(event.data)
    if (putDyImage.type === "putdyimage") {
      putUpDataFun(putDyImage.data)
    }
    if (putDyImage.type === "lodinIframe") {
      wetsetLodinIframe(false)
      // console.log('setAddInfoDatass', setAddInfoDatass)
      setAddInfoDatass.forEach((items, index) => {
        items.forEach((literImage, itous) => {
          literImage.old_url = literImage.url || ""
          // const imgae = literImage.url?.replace('obj/', '')
          // literImage.url = imgae ? imgae + '~110x110_q75.image' : ''
        })
      })
      iframe?.contentWindow.postMessage(
        { type: "dyimage", data: setAddInfoDatass },
        "*"
      )
    }
    if (putDyImage.type === "getHttpFunc") {
      const data = putDyImage.data
      dyrequest(putDyImage.data).then((res) => {
        iframe?.contentWindow.postMessage(
          { type: "putHttpFunc", data: res, id: putDyImage.id },
          "*"
        )
      })
    }
    if (putDyImage.type === "loginStatus") {
      // console.log('登陆状态', putDyImage)
      if (putDyImage.data.status) {
        // console.log('已经登陆')
        Modal.confirm({
          title: "提示",
          content: "是否批量Ai生成图片",
          okText: "是",
          cancelText: "否",
          onOk: (clear) => {
            iframe?.contentWindow.postMessage(
              {
                type: "createAi",
                data: {
                  index: -1
                }
              },
              "*"
            )
            clear()
          }
        })
      }
    }
  } catch (error) {
    // console.log('error', error)
  }
}
function AiOpenImageComp(props: any) {
  const [addIfameStatus, setAddIfameStatus] = useState(false)
  const [lodinIframe, setLodinIframe] = useState(true)
  const [putDataStatus, setPutDataStatus] = useState(false)
  wetsetLodinIframe = setLodinIframe
  if (!props) return null
  // console.log('props', props)
  const {
    type = "",
    visible = false,
    onCancel = () => { },
    setAddInfoData = [],
    product_id,
    img_format = 1,
    onChangeImage = null
  } = props
  globChangeImage = onChangeImage
  let { userShopId = "" } = store.getState().jinritemaiShops
  setAddInfoDatass = setAddInfoData
  const [iframeFoerm, setIframeFoer] = useState<any>(null)
  const [upLiter, setUpLiter] = useState<any>(null)
  function clearBox() {
    if (setImageTime) return
    setImageTime = setTimeout(() => {
      clearTimeout(setImageTime)
      setImageTime = null
    }, 1000)
    Modal.warning({
      title: "提示",
      content: "您还未发布，关闭后将不会保存您的修改，是否确认关闭？",
      okText: "确定",
      cancelText: "取消",
      onOk: (clear) => {
        window.removeEventListener("message", lengthcdata, false)
        setLodinIframe(true)
        onCancel(false)
        clear()
      }
    })
  }
  function addLenten() {
    window.addEventListener("message", lengthcdata)
  }
  const getImagesRef = useRef<any>(null)
  let apiter = img_format == 1 ? 1 : 1.33333
  return (
    <>
      <Modal
        size="small"
        width={1300}
        visible={visible}
        title="AI图片生成"
        footer={
          <Space>
            <Button
              size="mini"
              type="primary"
              onClick={() => {
                // iframeFoerm?.contentWindow.postMessage({ type: 'getUserData' }, '*')
                // console.log('getImagesRef', getImagesRef.current.someMethod())
                const getIteltr = getImagesRef.current?.someMethod() || null
                if (getIteltr) {
                  setUpLiter(getIteltr)
                  setPutDataStatus(true)
                  // putUpDataFun(getIteltr)
                }
              }}>
              发布
            </Button>
            <Button size="mini" onClick={() => clearBox()}>
              关闭
            </Button>
          </Space>
        }
        // onOk={() => {
        //     iframeFoerm?.contentWindow.postMessage({ type: 'getUserData' }, '*')
        // }}
        // closable={false}
        // okText="发布"
        // cancelText="关闭"
        bodyStyle={{
          padding: 0
        }}
        wrapClassName="addBodersModal"
        mask={true}
        maskClosable={true}
        onCancel={() => clearBox()}
        destroyOnClose={true}
      >
        <AiImage setAddInfoData={setAddInfoData} ref={getImagesRef} img_format={img_format} product_id={product_id} />
        {/* <Spin spinning={lodinIframe}>

        <iframe
          src={`https://lntelliai.com/imageAI/imageCopy?s=1&shop_id=${userShopId}&type=${type}&product_id=${product_id}&img_format=${img_format}`}
          id="iframe"
          onLoad={(e) => {
            iframe = e.target

            setIframeFoer(iframe)
            addLenten()

          }}
          style={{
            width: "100%",
            height: "785px"
          }}
          frameBorder="0"></iframe>
      </Spin> */}
      </Modal>
      <Modal
        title="确认发布"
        visible={putDataStatus}
        zIndex={99999}
        onCancel={() => {
          setPutDataStatus(false)
        }}
        onOk={() => {
          setPutDataStatus(false)
          putUpDataFun(upLiter)
        }}
      >
        <Space direction="vertical" style={{
          width: '100%',
        }}>

          {upLiter && upLiter.map((item: any, index: number) => {
            if (!item[0].url) return null
            return <Space direction="vertical" key={index} style={{
              width: '100%',
              border: '1px solid #ccc',
              padding: 10,
              borderRadius: 4,
            }}>
              <span>第 {index + 1} 组</span>
              <Space>
                <span>原图：</span>
                {item.map((item2: any, index2: number) => {
                  return <ImgDefault imgSrc={item2.old_url} width={60} height={60 * apiter} key={index2}></ImgDefault>
                })}
              </Space>
              <Space>
                <span>修改：</span>
                {item.map((item2: any, index2: number) => {
                  if (item2.url === item2.old_url) return <div key={index2} style={{
                    width: 60,
                    height: 60,
                    lineHeight: '60px',
                    textAlign: 'center',
                    border: '1px solid #ccc',
                    borderRadius: 4
                  }}>未修改</div>
                  return <ImgDefault imgSrc={item2.url} width={60} height={60 * apiter} key={index2}></ImgDefault>
                })}
              </Space>

            </Space>
          })
          }
        </Space>

      </Modal>
    </>

  )
}
export default AiOpenImageComp
